package org.mango.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.mango.pojo.UnixTime;

import java.util.Date;

/**
 * Created by meigang on 2019/8/8.
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
    private ByteBuf buf;

    /*@Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        buf = ctx.alloc().buffer(4);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        buf.release(); // (1)
        buf = null;
    }*/

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /*
        ByteBuf m = (ByteBuf) msg; // (1)
        try {
            //2208988800为1900年1月1日00:00:00~1970年1月1日00:00:00的总秒数
            long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
            System.out.println(new Date(currentTimeMillis));
            ctx.close();
        } finally {
            m.release();
        }
        */
        System.out.println("2.再将数据转换为时间输出");
        //ByteBuf m = (ByteBuf) msg;
        //ByteBuf buf = ctx.alloc().buffer(4);
        //buf.writeBytes(m); // (2)
        //m.release();

        //if (buf.readableBytes() >= 4) { // (3)
//            long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
//            System.out.println(new Date(currentTimeMillis));
//            ctx.close();
        //}

        UnixTime m = (UnixTime) msg;
        System.out.println(m);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
